package com.web.exiaodao.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.exiaodao.business.entity.Wish;
import com.web.exiaodao.business.repository.WishRepository;
import com.web.exiaodao.business.service.WishService;

@Service("WishService")
@Transactional(readOnly = false)
public class WishServiceImpl extends BaseService<Wish> implements WishService {

	@Autowired
	private WishRepository wishRepository;
	
	/**
	 * 查询单条Wish信息
	 * //@param tId
	 * @return 返回单个Wish对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Wish> findOne(Long modelId) throws BusinessException {
		Wish obj = new Wish();
		if(modelId != 0){
			obj = wishRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<Wish> xr = new XaResult<Wish>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(obj);
		} else {
			throw new BusinessException(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的Wish数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象Wish集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<Wish>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<Wish> page = wishRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), Wish.class), pageable);
		XaResult<Page<Wish>> xr = new XaResult<Page<Wish>>();
		xr.setObject(page);
		return xr;
	}

	/**
	 * 分页查询状态status的Wish数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象Wish集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<Wish>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<Wish> page = wishRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), Wish.class), pageable);
		XaResult<Page<Wish>> xr = new XaResult<Page<Wish>>();
		xr.setObject(page);
		return xr;
	}

	/**
	 * 保存Wish信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<Wish> saveOrUpdate(Wish model) throws BusinessException {
		Wish obj = null;
		if(XaUtil.isNotEmpty(model.getId())){
			obj = wishRepository.findOne(model.getId());
		}else{
			obj = new Wish();
		}
		obj.setWishDate(XaUtil.isNotEmpty(model.getWishDate()) ? model.getWishDate() : obj.getWishDate());
		obj.setContext(XaUtil.isNotEmpty(model.getContext()) ? model.getWishDate() : obj.getContext());
		obj = wishRepository.save(obj);
		XaResult<Wish> xr = new XaResult<Wish>();
		xr.setObject(obj);
		return xr;
	}

	/**
	 * 修改Wish状态，可一次修改多条   3删除  -1锁定  1正常
	 * //@param userId
	 * @param modelIds
	 * @param status
	 * @return 返回Wish对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<Wish> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<Wish> xr = new XaResult<Wish>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				Wish obj = wishRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = wishRepository.save(obj);
				} else {
					throw new BusinessException(XaConstant.Message.object_not_find);
				}
			}
		}
		return xr;
	}
	/**
	 * 查询心愿单，分页查询，用户名
	 */
	@Override
	public XaResult<Page<Wish>> findNotepadList(Integer nextPage, Integer pageSize, Map<String, Object> filterParams)
			throws BusinessException {
		//select f.id,f.context,u.user_name,f.wish_date from tb_xa_wish f left join tb_xa_user u on u.id = f.user_id WHERE f.STATUS<> 3 ORDER BY f.create_time
				StringBuffer sql=new StringBuffer("select f.id,f.context,u.user_name,f.wish_date ");
				sql.append("from tb_xa_wish f left join tb_xa_user u on u.id = f.user_id ");
				sql.append(" WHERE f.STATUS<> ").append(XaConstant.Status.delete);
				//统计数据库中数据个数
				StringBuffer sql1=new StringBuffer("select count(*) ");
				sql1.append("from tb_xa_wish f left join tb_xa_user u on u.id = f.user_id ");
				sql1.append(" WHERE f.STATUS<> ").append(XaConstant.Status.delete);
				//查询条件
						
						if(XaUtil.isNotEmpty(filterParams.get("EQ_userName"))){
							sql.append(" AND u.user_name= '").append(filterParams.get("EQ_userName")).append("' ");
							sql1.append(" AND u.user_name= '").append(filterParams.get("EQ_userName")).append("' ");
						}
						
						if(XaUtil.isNotEmpty(filterParams.get("LIKE_context"))){
							sql.append(" AND f.context ").append(" like '%").append(filterParams.get("LIKE_context")).append("%' ");
							sql1.append(" AND f.context ").append(" like '%").append(filterParams.get("LIKE_context")).append("%' ");
						}
						if(XaUtil.isNotEmpty(filterParams.get("LTE_wishDate"))){
							sql.append(" AND f.wish_date <= '").append(filterParams.get("LTE_wishDate")).append("' ");;
							sql1.append(" AND f.wish_date <= '").append(filterParams.get("LTE_wishDate")).append("' ");;
						}
						if(XaUtil.isNotEmpty(filterParams.get("BETWEEN_wishDate"))){
							String s = (String) filterParams.get("BETWEEN_wishDate");
							String[] str = s.split(",");
							sql.append(" AND f.wish_date between '").append(str[0]).append("' and '").append(str[1]).append("' ");;
							sql1.append(" AND f.wish_date between '").append(str[0]).append("' and '").append(str[1]).append("' ");;
						}
						sql.append(" ORDER BY f.wish_date DESC");
						sql1.append(" ORDER BY f.wish_date DESC");
						List<Object[]> objs=this.query(sql.toString(), nextPage*pageSize, pageSize);
						List<Wish> vos=new ArrayList<Wish>();
						
						for (Object[] obj : objs) {	
							Wish vo = new Wish();
							vo.setId(Long.valueOf(obj[0].toString()));
							vo.setContext(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
							vo.setUserName(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
							vo.setWishDate(XaUtil.isEmpty(obj[3])?"":obj[3].toString());
							vos.add(vo);
						}
						//执行查询语句
						List<Object[]> obj1=this.query(sql1.toString(), null, null);
						//将得到的查询结果强转成int类型
						int count=Integer.parseInt(obj1.get(0)+"");				
						//调用分页
						Page<Wish> page= new MyPage<Wish>(nextPage.intValue(),pageSize.intValue(),vos,count);
						//创建结果集对象xr
						XaResult<Page<Wish>> xr=new XaResult<Page<Wish>>();
						//将page放入xr
						xr.setObject(page);
						return xr;
	}
	
}
